package com.lexue.articlesync.controller;

import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.data.MutableDataSet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Markdown转换控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/markdown")
@RequiredArgsConstructor
public class MarkdownController {
    
    // Markdown解析器配置
    private final Parser parser;
    private final HtmlRenderer renderer;
    
    public MarkdownController() {
        MutableDataSet options = new MutableDataSet();
        this.parser = Parser.builder(options).build();
        this.renderer = HtmlRenderer.builder(options).build();
    }
    
    /**
     * 将Markdown内容转换为HTML
     */
    @PostMapping("/convert")
    public ResponseEntity<Map<String, Object>> convertMarkdownToHtml(@RequestBody Map<String, String> request) {
        try {
            String markdownContent = request.get("content");
            
            if (markdownContent == null || markdownContent.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("Markdown内容不能为空"));
            }
            
            // 解析Markdown并转换为HTML
            Node document = parser.parse(markdownContent);
            String htmlContent = renderer.render(document);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("html", htmlContent);
            response.put("originalLength", markdownContent.length());
            response.put("htmlLength", htmlContent.length());
            
            log.debug("Markdown转换成功: {} 字符 -> {} 字符HTML", 
                     markdownContent.length(), htmlContent.length());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Markdown转换失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("Markdown转换失败: " + e.getMessage()));
        }
    }
    
    /**
     * 验证Markdown内容
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateMarkdown(@RequestBody Map<String, String> request) {
        try {
            String markdownContent = request.get("content");
            
            if (markdownContent == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("内容不能为空"));
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("valid", true);
            response.put("length", markdownContent.length());
            response.put("lines", markdownContent.split("\n").length);
            
            // 统计一些基本信息
            Map<String, Integer> stats = new HashMap<>();
            stats.put("headers", countMatches(markdownContent, "^#+\\s"));
            stats.put("links", countMatches(markdownContent, "\\[([^\\]]+)\\]\\(([^\\)]+)\\)"));
            stats.put("images", countMatches(markdownContent, "!\\[([^\\]]*)\\]\\(([^\\)]*)\\)"));
            stats.put("codeBlocks", countMatches(markdownContent, "```"));
            response.put("stats", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Markdown验证失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("验证失败: " + e.getMessage()));
        }
    }
    
    /**
     * 计算正则表达式匹配次数
     */
    private int countMatches(String text, String regex) {
        try {
            return text.split(regex).length - 1;
        } catch (Exception e) {
            return 0;
        }
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}